<template>
  <div class="service_page_manager">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="syncclick"> 同步页面数据 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="disabledBatchBtn">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 关键词搜索 -->
      <div class="search">
        <el-select
          v-model="servicePageSearch.type"
          placeholder="页面类型"
          filterable
          clearable
          @change="getList"
          @clear="getList"
        >
          <el-option
            v-for="item in pageTypeOption"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model.trim="servicePageSearch.name"
          placeholder="页面名称"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <el-input
          v-model.trim="servicePageSearch.title"
          placeholder="页面标题"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search></Search>
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <!-- 列表表格 -->
    <div class="table">
      <el-table
        ref="tableDom"
        v-loading="tableLoading"
        element-loading-text="加载中..."
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        @selection-change="handleChange"
      >
        <!--选择-->
        <el-table-column type="selection" width="50" fixed :align="'center'" />

        <!--序号-->
        <el-table-column type="index" label="序号" width="50" fixed="left" :align="'center'" />

        <!--页面类型-->
        <el-table-column prop="type" label="页面类型" width="118">
          <template #default="scope">
            <span v-if="scope.row.type == 1">用户端</span>
            <span v-else-if="scope.row.type == 2">工程师</span>
            <span v-else>仓库出入库端</span>
          </template>
        </el-table-column>

        <!--页面名称-->
        <el-table-column prop="name" label="页面名称" width="160" />

        <!--页面链接-->
        <el-table-column show-overflow-tooltip prop="path" label="页面链接">
          <template #default="scope">
            {{ scope.row.path }}
          </template>
        </el-table-column>

        <!--更新时间-->
        <el-table-column prop="updateTime" label="更新时间" width="128" />

        <!--状态-->
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
              <HStatus v-else>启用</HStatus>
            </div>
          </template>
        </el-table-column>

        <!--操作-->
        <el-table-column fixed="right" label="操作" width="170">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink
                :data-clipboard-text="scope.row.path"
                @click="handleClipboard(scope.row.path, $event)"
                >复制链接</HLink
              >
              <HLink v-if="!scope.row.status" @click="getGenerate(scope.row)">二维码</HLink>
              <HLink @click="modifyClick(scope.row)">编辑</HLink>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="fieldTotal"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>
  </div>

  <!-- 修改  弹窗 -->
  <h-dialog v-model="addDialog" :title="modifytitle" :loading="fieldLoading">
    <el-form
      ref="formRef"
      label-position="top"
      inline-message
      class="modal_form_content"
      :rules="rules"
      :model="ruleForm"
    >
      <el-form-item label="页面名称" prop="name">
        <el-input v-model.trim="ruleForm.name" placeholder="请输入页面名称" disabled />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="ruleForm.type" disabled>
          <el-option
            v-for="(item, index) in pageTypeOption"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="页面标题" prop="title">
        <el-input v-model.trim="ruleForm.title" clearable placeholder="请输入页面标题" />
      </el-form-item>
      <el-form-item label="状态" class="same_line" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :value="false" size="small">启用</el-radio>
          <el-radio :value="true" size="small">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
      <HButton is-modal @click="addDialog = false">取消</HButton>
    </template>
  </h-dialog>

  <!-- 二维码弹窗 -->
  <h-dialog v-model="qrDialog" title="二维码详情" :loading="qrLoading" :width="800">
    <div class="qr_code_detail_modal">
      <div class="body">
        <div class="preview_container">
          <div class="qr_code_preview">
            <!-- 二维码标题 -->
            <div class="gen-title">
              <div
                v-if="dataQr.qrStyleType !== 1"
                class="gen-top"
                :style="
                  dataQr.qrStyleType === 3
                    ? 'background:' + dataQr.qrBackgroundColor + '; color:' + dataQr.qrTextColor
                    : ''
                "
              >
                {{ dataQr.qrTitle }}
              </div>
            </div>
            <!-- 二维码 -->
            <div class="gen-center">
              <vue-qr
                id="qrcode"
                :text="qrContentPath"
                :bind-element="true"
                :logo-corner-radius="0"
                :logo-src="generateLogo"
                :logo-margin="3"
              ></vue-qr>
            </div>
            <div style="height: 20px">
              <!-- 二维码文案 -->
              <div v-show="dataQr.qrStyleType != 1" class="gen-foot">
                {{ dataQr.qrProgramme }}
              </div>
            </div>
          </div>

          <div class="download_btn" @click="saveImg">
            <i class="iconfont icon-xiazai"></i>
            下载二维码
          </div>
        </div>

        <div class="config">
          <div class="header">
            <div class="item">
              <div class="label">页面名称:</div>
              <div class="value">{{ qrPageState.name }}</div>
            </div>
            <div class="item">
              <div class="label">页面类型:</div>
              <div
                v-for="(item, index) in pageTypeOption"
                v-show="item.value == qrPageState.type"
                :key="index"
                class="value"
                >{{ item.name }}</div
              >
            </div>
          </div>
          <div class="title">二维码标题及样式编辑</div>
          <div>
            <el-form ref="refDom" :rules="rules" :model="dataQr" inline-message>
              <div class="icon">
                <div class="label">图标</div>
                <div class="icons">
                  <h-image
                    v-for="(img, index) in dataQr.pageIcons"
                    :key="index"
                    :width="50"
                    :height="50"
                    :padding="2"
                    :src="img.image"
                    :preview-src-list="dataQr.pageIcons.map((item) => item.image)"
                    :mask-btn-gap="3"
                    :initial-index="index"
                    :mask-height="24"
                    mask-height-unit="px"
                    :border-color="img.select ? '#007cff' : '#ebeef5'"
                    @del="delImg(img, index)"
                    @img-click="selectImg(img, index)"
                  >
                    <template #contentMask>
                      <div class="selected_container">
                        <i v-if="img.select" class="iconfont icon-dagou"></i>
                      </div>
                    </template>
                  </h-image>
                  <el-upload
                    v-if="dataQr.pageIcons.length < 5"
                    action="#"
                    multiple
                    :show-file-list="false"
                    accept="image/*"
                    :auto-upload="false"
                    class="upload-picture"
                    @change="getProImages"
                  >
                    <el-icon :size="24" color="#007cff">
                      <UploadFilled />
                    </el-icon>
                  </el-upload>
                  <h-image
                    :width="50"
                    :height="50"
                    :padding="2"
                    :src="clearQrCodeLogo"
                    :show-mask="false"
                    @img-click="onClearLogo"
                  />
                </div>
              </div>

              <div class="style">
                <div class="title">样式</div>
                <el-form-item v-model="dataQr.qrStyleType" size="large">
                  <div
                    class="gen-label label1"
                    :style="{ borderColor: dataQr.qrStyleType === 1 ? '#007cff' : '' }"
                    @click="handleChange1(1)"
                  >
                    <template v-if="dataQr.qrStyleType === 1">
                      <i class="iconfont icon-dagou"></i>
                    </template>
                  </div>

                  <div
                    class="gen-label label2"
                    :style="{ borderColor: dataQr.qrStyleType === 2 ? '#007cff' : '' }"
                    @click="handleChange1(2)"
                  >
                    <div class="hd">
                      <template v-if="dataQr.qrStyleType === 2">
                        <i class="iconfont icon-dagou"></i>
                      </template>
                    </div>
                    <div class="hd1"></div>
                  </div>
                  <div
                    class="gen-label label3"
                    :style="{ borderColor: dataQr.qrStyleType === 3 ? '#007cff' : '' }"
                    @click="handleChange1(3)"
                  >
                    <div
                      class="hd"
                      :style="
                        dataQr.qrStyleType === 3
                          ? 'background:' +
                            dataQr.qrBackgroundColor +
                            '; color:' +
                            dataQr.qrTextColor
                          : ''
                      "
                    >
                      <template v-if="dataQr.qrStyleType === 3">
                        <i class="iconfont icon-dagou"></i>
                      </template>
                    </div>
                    <div class="hd1"></div>
                  </div>
                </el-form-item>
              </div>

              <el-form-item
                v-show="dataQr.qrStyleType != 1"
                label="标题"
                prop="qrTitle"
                class="el-qrTitle"
                label-width="46"
              >
                <el-input
                  v-model.trim="dataQr.qrTitle"
                  clearable
                  placeholder="请输入标题"
                  maxlength="10"
                />
              </el-form-item>
              <el-form-item
                v-show="dataQr.qrStyleType != 1"
                label="文案"
                prop="qrProgramme"
                label-width="46"
                style="margin-top: 12px"
              >
                <el-input
                  v-model.trim="dataQr.qrProgramme"
                  clearable
                  placeholder="请输入文案"
                  maxlength="10"
                />
              </el-form-item>

              <el-form-item
                v-show="dataQr.qrStyleType == 3"
                label="二维码标题字体颜色"
                class="el-color"
              >
                <el-color-picker v-model="dataQr.qrTextColor" :predefine="predefineColors" />
              </el-form-item>
              <el-form-item
                v-show="dataQr.qrStyleType == 3"
                label="二维码标题背景颜色"
                class="el-color"
              >
                <el-color-picker v-model="dataQr.qrBackgroundColor" :predefine="predefineColors" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <HButton is-modal type="primary" @click="SaveGenerate(refDom)">保存</HButton>
      <HButton is-modal @click="qrDialog = false">取消</HButton>
    </template>
  </h-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, h } from 'vue'
  import { ElDivider, FormInstance, UploadFile } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Warning, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import Pagination from '@/components/Pagination/index.vue'
  import vueQr from 'vue-qr/src/packages/vue-qr.vue'
  import html2canvas from 'html2canvas'
  import { systemAcceUpload } from '@/api/upload'
  import {
    getSyncService,
    getSyncList,
    getmodifyEmp,
    getBatchEnaDis,
    getgenerateInfo,
    getgeneratedata,
  } from '@/api/servicepage'
  import handleClipboard from '@/utils/clipboard' //复制
  import clearQrCodeLogo from '@/assets/image/pages/info_set/service_page/clear_qr_code_logo.png'
  import { HMessageBox } from '@/components/common/message'

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const tableLoading = ref(false) // 列表表格加载动画
  const qrLoading = ref(false) // 二维码弹窗加载动画
  const disabledBatchBtn = ref(true) // 批量操作按钮禁用状态
  const tableData = ref([]) // 表格数据
  const selecttion = ref([]) // 表格选中的数据
  const addDialog = ref(false)
  const qrDialog = ref(false) // 二维码弹窗
  const fieldLoading = ref(false) //加载指示器或进度条
  const modifytitle = ref() //修改标题
  const pagination = ref() // 分页dom
  const tableDom = ref() //列表tom
  const fieldTotal = ref() // 总数目
  const fieldId = ref('') // 字段ID
  const generateLogo = ref('') //二维码logo
  const qrContentPath = ref('') // 二维码内容路径
  const servicePageSearch = ref({
    page: 1,
    limit: 50,
    type: '', // 类型：1-公司报单端，2-部门端，3-仓库出入库端
    name: '', // 页面名称
    title: '', // 页面标题
  })
  // 页面类型
  const pageTypeOption = [
    {
      value: '1',
      name: '公司报单端',
    },
    {
      value: '2',
      name: '部门端',
    },
    {
      value: '3',
      name: '仓库出入库端',
    },
  ]
  // 页面类型
  const qrPageState = reactive({
    type: '',
    name: '',
    title: '',
  })

  // 表单元素
  const formRef = ref()
  const refDom = ref()
  const ruleForm = reactive({
    id: null,
    name: '',
    type: null,
    title: '',
    status: false,
  })
  let dataQr = ref({
    delPageIconIds: [],
    id: null,
    pageIcons: [],
    qrProgramme: '',
    qrStyleType: 1,
    qrTitle: '',
    qrTextColor: '', //二维码标题颜色
    qrBackgroundColor: '', //二维码背景颜色
  })

  //选择二维码标题颜色
  const qrTitleDefColor = ref('#FBFBFB') // 二维码标题默认颜色
  const qrTitleBackgroundDefColor = ref('#007CFF') // 二维码标题背景默认颜色
  // 预选颜色值
  const predefineColors = ref([
    '#ff4500',
    '#ff8c00',
    '#ffd700',
    '#90ee90',
    '#00ced1',
    '#1e90ff',
    '#c71585',
  ])
  //验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    title: [{ required: true, message: '请选择类型', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
    status: [{ required: true, message: '请选择类型', trigger: 'blur' }],
    qrTitle: [{ required: true, message: '请输入标题', trigger: ['change', 'blur'] }],
  })

  //打开二维码弹窗（同时获取二维码详细数据）
  const getGenerate = async (obj) => {
    qrDialog.value = true
    qrLoading.value = true
    fieldId.value = obj.id
    generateLogo.value = ''
    qrContentPath.value = ''
    await getgenerateInfo(fieldId.value).then((res) => {
      qrLoading.value = false
      if (res.data.code === 20000) {
        const data = res.data.data.row
        qrPageState.type = data.type
        qrPageState.name = data.name
        qrPageState.title = data.title
        qrContentPath.value = data.path
        dataQr.value = data
        dataQr.value.delPageIconIds = []
        if (dataQr.value.pageIcons) {
          generateLogo.value = dataQr.value.pageIcons.filter((f) => f.select)[0]?.image
        }
        if (!data.qrTextColor) {
          dataQr.value.qrTextColor = qrTitleDefColor.value
        }
        if (!data.qrBackgroundColor) {
          dataQr.value.qrBackgroundColor = qrTitleBackgroundDefColor.value
        }
      }
    })
  }
  //获取服务页面列表
  const getList = async (val = true) => {
    if (val) pagination.value.setPage()
    servicePageSearch.value.page = pagination.value.current
    servicePageSearch.value.limit = pagination.value.size
    tableLoading.value = true
    await getSyncList(servicePageSearch.value).then((res) => {
      tableLoading.value = false
      tableData.value = res.data.data.rows
      fieldTotal.value = parseInt(res.data.data.total)
    })
  }

  //同步服务
  const syncclick = async () => {
    await getSyncService().then((resp) => {
      ElMessage({
        message: resp.data.message,
        type: resp.data.code !== 20000 ? 'error' : 'success',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (resp.data.code === 20000) {
        getList()
      }
    })
  }

  //修改服务
  const modifyClick = async (obj) => {
    addDialog.value = true
    modifytitle.value = '编辑服务'
    fieldId.value = obj.id
    ruleForm.title = obj.title
    ruleForm.name = obj.name
    ruleForm.type = obj.type
    ruleForm.status = obj.status
  }

  //封装服务页面数据
  const EncapData = () => {
    const data = {
      id: fieldId.value,
      name: ruleForm.name,
      title: ruleForm.title,
      status: ruleForm.status,
      type: ruleForm.type,
    }
    fieldLoading.value = true
    getmodifyEmp(data).then((res) => {
      fieldLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success == true) {
        addDialog.value = false
        getList()
      }
    })
  }

  //保存服务页面数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        EncapData()
      }
    })
  }

  // 列表多选项框事件
  const handleChange = (val) => {
    selecttion.value = []
    if (val.length > 0) {
      val.forEach((item) => {
        selecttion.value.push(item.id)
      })
    }
  }

  //批量操作方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: '请选择页面',
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: 'warning',
      title: '提示',
      message: `确认${type}选中的类型?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            dialog.value = false
          }
        })
      }
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量修改状态
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', getBatchEnaDis, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', getBatchEnaDis, selecttion.value, true, '')
    }
  }

  //上传图片 二维码logo
  const getProImages = (uploadFile: UploadFile) => {
    if (dataQr.value.pageIcons.length >= 5) {
      HMessageBox.error('上传数量不能超过5张')
      return
    }
    dataQr.value.pageIcons.push({
      id: null,
      image: URL.createObjectURL(uploadFile.raw),
      select: false,
      file: uploadFile.raw,
    })
  }

  // 删除图片
  function delImg(img, index) {
    if (img.select == true) {
      generateLogo.value = ''
    }
    if (img.id) {
      dataQr.value.delPageIconIds.push(img.id)
    }
    dataQr.value.pageIcons = dataQr.value.pageIcons.filter((o, i) => {
      return i != index
    })
  }
  //选择图片
  const selectImg = (img, index) => {
    dataQr.value.pageIcons = dataQr.value.pageIcons.map((o, i) => {
      if (index == i) {
        if (o.select == true) {
          generateLogo.value = ''
          return { ...o, select: false }
        } else {
          generateLogo.value = o.image
          return { ...o, select: true }
        }
      } else {
        return { ...o, select: false }
      }
    })
  }

  const onClearLogo = () => {
    generateLogo.value = ''
    dataQr.value.pageIcons = dataQr.value.pageIcons.map((icon) => {
      return {
        ...icon,
        select: false,
      }
    })
  }

  //样式监听
  const handleChange1 = (newStyle: number) => {
    dataQr.value.qrStyleType = newStyle
  }

  //封装二维码数据
  const EnGenerate = async () => {
    qrLoading.value = true
    if (dataQr.value.pageIcons.length > 0) {
      for (let key = 0; key < dataQr.value.pageIcons.length; key++) {
        const imgObj = dataQr.value.pageIcons[key]
        if (imgObj.file) {
          let imgI = imgObj.file
          await systemAcceUpload([imgI]).then((res) => {
            if (res.data.success) {
              dataQr.value.pageIcons[key].image = res.data.data.rows[0]
              delete dataQr.value.pageIcons[key].file
            }
          })
        }
      }
    }
    getgeneratedata(dataQr.value).then((res) => {
      qrLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success) {
        qrDialog.value = false
        getList()
      }
    })
  }

  //保存二维码数据
  const SaveGenerate = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        EnGenerate()
      }
    })
  }

  //下载二维码
  const saveImg = () => {
    const dialogElement = document.querySelector('.qr_code_preview') as HTMLElement // 显式断言为 HTMLElement 类型
    if (dialogElement) {
      html2canvas(dialogElement).then((canvas) => {
        const image = canvas.toDataURL('image/png')
        const a = document.createElement('a')
        a.href = image
        a.download = 'qr_code.png'
        a.click()
      })
    }
  }

  // 监听列表选中的数据
  watch(
    () => selecttion.value,
    () => {
      disabledBatchBtn.value = true
      if (selecttion.value.length > 0) {
        disabledBatchBtn.value = false
      }
    },
  )

  onMounted(() => {
    getList()
  })

  defineExpose({
    getList,
  })
</script>

<style scoped lang="scss">
  @import './ServiceCard.scss';
</style>
